import { PlusOutlined, CarryOutOutlined, FormOutlined } from '@ant-design/icons';
import { Button, message, Tree, Drawer, Layout } from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import { useIntl, FormattedMessage } from 'umi';
import { PageContainer } from '@ant-design/pro-layout';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProCard from '@ant-design/pro-card';
import ProTable from '@ant-design/pro-table';
import ProForm, {
  BetaSchemaForm,
  ModalForm,
  ProFormText,
  ProFormDigit,
  ProFormCascader,
  ProFormSelect,
  ProFormTreeSelect,
  ProFormTextArea,
  ProFormColumnsType
} from '@ant-design/pro-form';
import { permModuleList, permModuleAdd, permList, permAdd } from  '@/services/ant-design-pro/permModule';
import { transformList2Tree } from '@/utils/utils'

const { DirectoryTree } = Tree;

const valueEnum = {
  all: { text: '全部', status: 'Default' },
  open: {
    text: '未解决',
    status: 'Error',
  },
  closed: {
    text: '已解决',
    status: 'Success',
    disabled: true,
  },
  processing: {
    text: '解决中',
    status: 'Processing',
  },
};

const columns: ProColumns<API.PermItem>[] = [
  {
    title: <FormattedMessage id="pages.searchTable.titleDesc" defaultMessage="部门名称" />,
    dataIndex: 'perm_name',
    valueType: 'textarea',
  },
  {
    title: <FormattedMessage id="pages.searchTable.titleCallNo" defaultMessage="上级部门id" />,
    dataIndex: 'parent_id',
    search: false
  },
  {
    title: (
      <FormattedMessage id="pages.searchTable.titleUpdatedAt" defaultMessage="最近更新时间" />
    ),
    sorter: true,
    search: false,
    dataIndex: 'update_time',
    valueType: 'dateTime'
  },
  {
    title: (
      <FormattedMessage id="pages.searchTable.titleUpdatedAt" defaultMessage="创建时间" />
    ),
    sorter: true,
    search: false,
    dataIndex: 'create_time',
    valueType: 'dateTime'
  },
];

const columns1: ProFormColumnsType<API.PermItem>[] = [
  {
    title: '权限名称',
    dataIndex: 'perm_name',
    formItemProps: {
      rules: [
        {
          required: true,
          message: '此项为必填项',
        },
      ],
    },
    width: 'md',
  },
  {
    title: '所属模块',
    dataIndex: 'parent_id',
    valueType: 'select',
    valueEnum,
    width: 'm',
  },
  {
    title: '关联的url',
    dataIndex: 'labels',
    width: 'm',
  },
  {
    title: '显示顺序',
    key: 'show_order',
    dataIndex: 'show_order',
    valueType: 'digit',
  }
];
// /api/v1/permModule/
const SysPerm: React.FC = () => {
 /** 新建窗口的弹窗 */
 const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  /** 国际化配置 */
  const intl = useIntl();
  const [modalVisit, setModalVisit] = useState(false);
  const [permModules, setPermModules] = useState<any>([]);
  const [params, setParams] = useState<any>({pid: 0});
  let tempList: any[] = [
    {
      title: '全部',
      value: 0,
      key: 'all-0',
      id: 0,
      pid: 0
    }
  ];

  useEffect(() => {
    permModuleList().then(res => {
      const tree = transformList2Tree(res.data!.map((d) => ({
        title: d.module_name,
          value: d.id,
          key: d.id,
          id: d.id,
          pid: d.parent_id
      })))
      tempList = tempList.concat(tree)
      setPermModules(tempList)
    })
  }, [])

  const treeDataChange = (ids: any[]) => {
    setParams({
      pid: ids.join(',')
    })
  }

  return (
    <PageContainer>
      <div style={{display: 'flex', width: '100%'}}>
      <ProCard title="权限模块" headerBordered extra={
        <Button
          shape="circle"
          icon={<PlusOutlined />}
          onClick={() => {
            setModalVisit(true);
          }}
        />} style={{ maxWidth: 300 }}>
        {permModules.length > 0 && <DirectoryTree
          defaultSelectedKeys={['all-0']}
          showLine={false}
          showIcon={false}
          onSelect={treeDataChange}
          treeData={permModules}
        />}
      </ProCard>
      <ProTable<API.PermItem, API.PageParams>
        style={{flex:1, marginLeft: '20px'}}
        headerTitle={intl.formatMessage({
          id: 'pages.searchTable.title',
          defaultMessage: '查询表格',
        })}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              handleModalVisible(true);
            }}
          >
            <PlusOutlined /> <FormattedMessage id="pages.searchTable.new" defaultMessage="新建" />
          </Button>,
        ]}
        rowKey="key"
        search={{
          labelWidth: 120,
        }}
        columns={columns}
        request={permList}
        params={params}
      />

      </div>
      <ModalForm
        title="新建表单"
        layout="horizontal"
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 12 }}
        visible={modalVisit}
        onFinish={async (fields) => {
          const hide = message.loading('正在添加');
          if (fields.parent_id) {
            fields.parent_id = fields.parent_id[fields.parent_id.length - 1]
          }
          try {
            await permModuleAdd({ ...fields });
            hide();
            message.success('添加成功');
            return true;
          } catch (error) {
            hide();
            message.error('添加失败请重试！');
            return false;
          }
        }}
        onVisibleChange={setModalVisit}
      >
        <ProFormText name="module_name" label="模块名称" />
        <ProFormSelect
          name="module_type"
          label="模块类型"
          request={async () => [
            { label: '分组模块', value: 'all' },
            { label: '接口模块', value: 'open' },
          ]}
          placeholder="Please select a country"
          rules={[]}
        />
        <ProFormCascader
          name="parent_id"
          label="上级部门"
          request={async() => {
            const data = await permModuleList()
            console.log('上级部门', data)
            return transformList2Tree(data.data!.map((d) => ({
              label: d.module_name,
              value: d.id,
              id: d.id,
              pid: d.parent_id
            })))
          }}
        />
        <ProFormDigit
          label="显示顺序"
          name="show_order"
          fieldProps={{ precision: 0 }}
        />
      </ModalForm>

      <BetaSchemaForm
        visible={createModalVisible}
        onVisibleChange={handleModalVisible}
        layoutType={'ModalForm'}
        onFinish={async (values) => {
          const success = await permAdd(values as API.PermItem);
          if (success) {
            handleModalVisible(false);
          }
        }}
        columns={columns1}
      />
    </PageContainer>
  );
};

export default SysPerm;
